package com.tangsm.spring.boot.filter.common.filter;

import com.tangsm.spring.boot.filter.common.utli.HttpUtils;
import com.tangsm.spring.boot.filter.common.wrapper.RequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring OncePerRequestFilter 实现服务接口禁用过滤器
 * @author tangsm
 */
@Order(1)
@Component
public class ServiceDisableFilter extends OncePerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(ServiceDisableFilter.class);

    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request     请求
     * @param response    响应
     * @param filterChain 调用链
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        log.info("Spring OncePerRequestFilter 实现服务接口禁用过滤器，接口服务禁用过滤器，接口：{}", uri);

        // json请求打印body信息
        if (HttpUtils.isJsonContent(request)) {
            RequestWrapper requestWrapper = new RequestWrapper(request);
            String bodyString = requestWrapper.getBody();
            log.info("Spring OncePerRequestFilter 实现服务接口禁用过滤器，请求参数，Body：{}", bodyString);

            filterChain.doFilter(requestWrapper, response);
            return;
        }

        filterChain.doFilter(request, response);
    }
}
